import { ref, onMounted } from 'vue';

function useFps(autoStart) {
	
	const fps = ref(0);
	let key = null;
	let array = [];
	let lastTimeStamp = null;
	let interval = null;
	
	function start(duration = 1000) {
		stop();
		lastTimeStamp = null;
		interval = setInterval(() => {
			fps.value = Math.round(array.reduce((t, n) => t + n, fps.value) / (array.length + 1));
			array.length = 0;
		}, duration);
		document.addEventListener('visibilitychange', (e) => {
			lastTimeStamp = null;
		})
		calc();
	}
	
	function stop() {
		cancelAnimationFrame(key);
		clearInterval(interval);
	}
	
	function calc() {
		key = requestAnimationFrame((timestamp) => {
			if (lastTimeStamp) array.push(timestamp - lastTimeStamp);
			lastTimeStamp = timestamp;
			requestAnimationFrame(calc);
		})
	}
	
	if (autoStart) {
		start();
	}
	
	return {
		fps,
		start, stop
	}
	
}

export default useFps;